package com.ophiux.utils.wechat;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.UUID;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import com.ophiux.utils.common.JavaMd5Util;
import com.ophiux.utils.common.TenpayUtil;

public class WXServiceUtils {
	public static int CODE_XLH = 0;

	/**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
	 * 
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static Map doXMLParse(String strxml) throws Exception {
		if (null == strxml || "".equals(strxml)) {
			return null;
		}

		Map m = new HashMap();
		InputStream in = String2Inputstream(strxml);
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			Element e = (Element) it.next();
			String k = e.getName();
			String v = "";
			List children = e.getChildren();
			if (children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = getChildrenText(children);
			}
			m.put(k, v);
		}

		// 关闭流
		in.close();

		return m;
	}

	/**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
	 * 
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static Map doXMLParse1(String strxml) throws Exception {
		if (null == strxml || "".equals(strxml)) {
			return null;
		}

		Map m = new HashMap();
		InputStream in = String2Inputstream(strxml);
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			Element e = (Element) it.next();
			String k = e.getName();
			String v = "";
			List children = e.getChildren();
			if (children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				getChildrenText1(children, m);
			}
			if ("".equals(v)) {
				v = null;
			}
			m.put(k, v);
		}
		// 关闭流
		in.close();
		return m;
	}

	/**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
	 * 
	 * @param strxml
	 * @return
	 * @throws JDOMException
	 * @throws IOException
	 */
	public static Map doXMLParseOne(String strxml) throws Exception {
		if (null == strxml || "".equals(strxml)) {
			return null;
		}

		Map m = new HashMap();
		InputStream in = String2Inputstream(strxml);
		SAXBuilder builder = new SAXBuilder();

		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			Element e = (Element) it.next();
			String k = e.getName();
			String v = "";
			List children = e.getChildren();
			if (children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				getChildrenText1(children, m);
			}
			if ("".equals(v)) {
				v = null;
			}
			m.put(k, v);
		}

		// 关闭流
		// in.close();

		return m;
	}

	/**
	 * 获取子结点的xml
	 * 
	 * @param children
	 * @return String
	 */
	public static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if (!children.isEmpty()) {
			Iterator it = children.iterator();
			while (it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if (!list.isEmpty()) {
					sb.append(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}

		return sb.toString();
	}

	/**
	 * 获取子结点的xml
	 * 
	 * @param children
	 * @return String
	 */
	public static void getChildrenText1(List children, Map map) {
		StringBuffer sb = new StringBuffer();
		if (!children.isEmpty()) {
			Iterator it = children.iterator();
			while (it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				if ("".equals(value)) {
					value = null;
				}
				List list = e.getChildren();
				if (list.isEmpty()) {
					// v = e.getTextNormalize();
				} else {
					getChildrenText2(list, map);
				}
				map.put(name, value);
				// sb.append("<" + name + ">");
				// if (!list.isEmpty()) {
				// sb.append(getChildrenText(list));
				// }
				// sb.append(value);
				// sb.append("</" + name + ">");
			}
		}

		// return sb.toString();
	}

	/**
	 * 获取子结点的xml
	 * 
	 * @param children
	 * @return String
	 */
	public static void getChildrenText2(List children, Map map) {
		StringBuffer sb = new StringBuffer();
		if (!children.isEmpty()) {
			Iterator it = children.iterator();
			while (it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				if ("".equals(value)) {
					value = null;
				}
				map.put(name, value);
				// List list = e.getChildren();
				// sb.append("<" + name + ">");
				// if (!list.isEmpty()) {
				// sb.append(getChildrenText(list));
				// }
				// sb.append(value);
				// sb.append("</" + name + ">");
			}
		}

		// return sb.toString();
	}

	/**
	 * 根据集合生成签名
	 * 
	 * @param obj
	 * @return
	 */
	public static String createSignByMapGZH(Map<String, String> parameters, String api_token) {
		// parameters
		StringBuffer sb = new StringBuffer();

		// 所有参与传参的参数按照accsii排序（升序）
		List<String> list = new ArrayList<String>();
		Set<Entry<String, String>> set = parameters.entrySet();
		Iterator<Entry<String, String>> itt = set.iterator();
		while (itt.hasNext()) {
			Entry<String, String> next = itt.next();
			list.add(next.getKey());
		}

		List<String> resultList = assicSort(list);
		for (int i = 0; i < resultList.size(); i++) {
			String key = resultList.get(i);
			String value = parameters.get(resultList.get(i));
			if (null != value && !"".equals(value) && !"sign".equals(key) && !"key".equals(key)) {
				sb.append(key + "=" + value + "&");
			}
		}
		sb.append("key=" + api_token);
		System.out.println("待加密字符串" + sb.toString());
		String sign = null;
		try {
			sign = JavaMd5Util.md5Encode(sb.toString()).toUpperCase();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sign;
	}

	public static InputStream String2Inputstream(String str) {
		InputStream in = null;
		try {
			in = new ByteArrayInputStream(str.getBytes("utf-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return in;
	}

	/**
	 * 按照ASSIC码排序
	 * 
	 * @param list
	 * @return
	 */
	public static List<String> assicSort(List<String> list) {
		for (int i = 0; i < list.size(); i++) {
			for (int j = i + 1; j < list.size(); j++) {
				String before = list.get(i);
				String after = list.get(j);
				if (compareString(before, after) > 0) {
					// 交换
					String temp = list.get(i);
					list.set(i, list.get(j));

					list.set(j, temp);
				}
			}
		}

		return list;
	}

	/**
	 * 比较大小
	 * 
	 * @param before
	 * @param after
	 * @return
	 */
	public static int compareString(String before, String after) {
		int result = 0;
		char[] a = before.toCharArray();
		char[] b = after.toCharArray();
		if (a.length > 0 && b.length > 0) {
			if ((int) a[0] > (int) b[0]) {
				result = 1;
				return result;
			} else if ((int) a[0] < (int) b[0]) {
				result = -1;
				return result;
			} else {
				// 相等
				return compareString(before.substring(1, before.length()), after.substring(1, after.length()));
			}
		}

		return result;
	}

	/**
	 * 生成随机退款订单号
	 * 
	 * @author hhl
	 * @return
	 */
	public static synchronized String getRefundNo() {
		String mtext = null;
		String strRandom = TenpayUtil.buildRandom(4) + "";
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmsss");// 设置日期格式
		mtext = df.format(new Date()) + strRandom;
		CODE_XLH++;
		CODE_XLH = CODE_XLH % 100;
		mtext = mtext + CODE_XLH;
		return mtext;

	}

	/**
	 * 生成随机字符串
	 * 
	 * @author hhl
	 * @return
	 */
	public static String getNonceStr() {
		return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
	}

	/**
	 * 生成 uuid， 即用来标识一笔单，也用做 nonce_str
	 * 
	 * @return
	 */
	public static String getRandomString() { // length表示生成字符串的长度
		int length = 32;
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString().toUpperCase();
	}

}
